package com.pat.java.base.xml;

import java.io.File;
import java.io.FileReader;
import java.util.Hashtable;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParseXml {
	public static void main(String[] args) {
		try {

			File file = new File("files/person.xml");
			FileReader reader = new FileReader(file);
			//创建解些工厂实例
			SAXParserFactory spf = SAXParserFactory.newInstance();
			//创建解析器
			SAXParser sp = spf.newSAXParser();
			//创建处理类实例
			SAXHandler handler = new SAXHandler();
			//解析
			sp.parse(new InputSource(reader), handler);
			Hashtable<String, String> hashTable = handler.getTable();
			//输出数据

			System.out.println("教师信息表");
			System.out.println("姓名:" + (String) hashTable.get(new String("name")));
			System.out.println("学院:" + (String) hashTable.get(new String("college")));
			System.out.println("电话:" + (String) hashTable.get(new String("telephone")));
			System.out.println("职称:" + (String) hashTable.get(new String("title")));
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
};

//自定义处理类
class SAXHandler extends DefaultHandler {
	private Hashtable<String, String> table = new Hashtable<String, String>();
	private String currentElement = null;
	private String currentValue = null;

	public Hashtable<String, String> getTable() {
		return table;
	}
	//覆盖startElement方法，取出节点标签
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) {
		currentElement = qName;
	}

	//覆盖characters方法，取出节点值
	public void characters(char[] ch, int start, int length) throws SAXException {
		currentValue = new String(ch, start, length);
	}

	//覆盖endElement方法，放入Hashtable
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (currentElement.equals(qName))
			table.put(currentElement, currentValue);
	}
}